package org.rocket.spring.security.demo.web.async;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;


/**
 * @author He Peng
 * @create 2018-01-21 22:53
 * @update 2018-01-21 22:53
 * @updatedesc : 更新说明
 * @see
 */

@Component
public class MessageQueueListener implements ApplicationListener<ContextRefreshedEvent> {

    private Logger LOG = LoggerFactory.getLogger(MessageQueueListener.class);

    @Autowired
    private MockMessageQueue mockMessageQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        new Thread(() -> {
            while (true) {
                if (StringUtils.isNotBlank(this.mockMessageQueue.getCompleteOrder())) {
                    String orderNumber = this.mockMessageQueue.getCompleteOrder();
                    LOG.info("返回订单处理结果 ===> {} " , orderNumber);
                    this.deferredResultHolder.getDeferredResultMap()
                            .get(orderNumber).setResult("place order " + orderNumber + "success");
                    this.mockMessageQueue.setCompleteOrder(null);
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } , "MessageQueueListener-Thread").start();
    }
}
